import { FModule } from "../Support/FModule";
import { IModule } from "../Interfaces/IModule";
import { EventManager } from "./EventManager";
import { FEvent } from "../Event/FEvent";
import { CMDManager } from "./CMDManager";


export class ModuleManager
{
    private static _instance: ModuleManager = null;
    public static get instance(): ModuleManager 
    {
        if (!this._instance) this._instance = new ModuleManager();
        return this._instance;
    }
    private domains:{[key:string]:typeof FModule} = {};
    private modules:{[key:string]:IModule} ={};
    public constructor()
    {
        CMDManager.AddCMD("modules",()=>
        {
            for (let key in this.modules)
            {
                console.log("当前处于激活中模块======>",key);
            }
        },this);


        
    }
    /**设置模块映射 */
    public addModuleClass(moduleName:string,moduleClass:typeof FModule,force?:boolean):void
    {
        if(!force&&this.domains[moduleName]!=undefined)console.log("重复设置名称为 ",moduleName," 的模块！！！");
        else this.domains[moduleName] = moduleClass;
    }
    public removeModuleClass(moduleName:string):void
    {
    }
    public hasModule(moduleName:string,instanceName?:string):boolean
    {
        let name = this.convetName(moduleName,instanceName);
        return this.modules[name]!=null;
    }
    public addModule(m:IModule,moduleName:string,instanceName?:string):void
    {
        let name = this.convetName(moduleName,instanceName);
        if(this.modules[name]==undefined)this.modules[name]=m;
        else console.log("[ModuleManager]",moduleName," 中实例中已经存在！！！");
    }
    public getModule(moduleName:string,instanceName?:string):IModule
    {
        let name = this.convetName(moduleName,instanceName);
        if(this.modules[name]==null)
        {
            let clz = this.domains[moduleName];
            if(clz!=null)this.modules[name] = new clz();
        }
        return this.modules[name];
    } 
    public disposeModule(moduleName:string,instanceName?:string):void
    {
        let name = this.convetName(moduleName,instanceName);
        if(this.modules[name]==null)return;
        // console.log("销毁模块=====>",moduleName,instanceName);
        EventManager.dispatchEvent(new FEvent("OnDisposeModuleObject",this.modules[name]));
        this.modules[name].dispose();
        delete this.modules[name];
    }
    private convetName(moduleName:string,instanceName?:string):string
    {
        return moduleName+"_"+(instanceName?instanceName:moduleName);
    }
}
